package com.google.code.ufp.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

public final class XMPPReceiverServlet extends HttpServlet {

	private static final long serialVersionUID = -7280656051736677177L;
	
	private static final Logger log = Logger.getLogger(XMPPReceiverServlet.class.getName());

	@SuppressWarnings("serial")
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		XMPPService xmpp = XMPPServiceFactory.getXMPPService();
		Message message = xmpp.parseMessage(req);

		JID fromJid = message.getFromJid();
		String body = message.getBody();
		
		
		
		try {
            URL url = new URL(body);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer sb = new StringBuffer();
            
            String line;
            while ((line = reader.readLine()) != null) {
            	sb.append(line);
            }
            reader.close();
            
            Message msg = new MessageBuilder()
            .withRecipientJids(fromJid)
            .withBody(sb.toString())
            .build();

            boolean messageSent = false;
        if (xmpp.getPresence(fromJid).isAvailable()) {
            SendResponse status = xmpp.sendMessage(msg);
            messageSent = (status.getStatusMap().get(fromJid) == SendResponse.Status.SUCCESS);
        }

        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }
		

        
	}

}
